import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

Window {
    width: 400
    height: 600
    visible: true
    title: "ListView 数据交互示例"

    // 定义数据模型
    ListModel {
        id: fruitModel
        ListElement { name: "苹果"; price: "5.0" }
        ListElement { name: "香蕉"; price: "3.5" }
        ListElement { name: "橙子"; price: "4.0" }
    }

    ColumnLayout {
        anchors.fill: parent
        spacing: 10
        
        // 添加新水果的输入区域
        RowLayout {
            Layout.margins: 10
            TextField {
                id: nameInput
                placeholderText: "水果名称"
                Layout.fillWidth: true
            }
            TextField {
                id: priceInput
                placeholderText: "价格"
                Layout.fillWidth: true
            }
            Button {
                text: "添加"
                onClicked: {
                    if (nameInput.text && priceInput.text) {
                        fruitModel.append({"name": nameInput.text, "price": priceInput.text})
                        nameInput.text = ""
                        priceInput.text = ""
                    }
                }
            }
        }

        // ListView显示区域
        ListView {
            id: listView
            Layout.fillWidth: true
            Layout.fillHeight: true
            model: fruitModel
            delegate: ItemDelegate {
                width: listView.width
                contentItem: RowLayout {
                    Text { text: name; Layout.fillWidth: true }
                    Text { text: price + "元" }
                    Button {
                        text: "删除"
                        onClicked: fruitModel.remove(index)
                    }
                }
            }
        }
    }
} 
